package com.ydgk.servlet;

import com.ydgk.bean.Login;
import com.ydgk.bean.User;
import com.ydgk.service.LoginService;
import com.ydgk.service.UserService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

@WebServlet(name = "LoginServlet", urlPatterns = "/LoginServlet.action")
public class LoginServlet extends BaseServlet {
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session=request.getSession();
        Login login=new Login();
        try {
            BeanUtils.populate(login, request.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        LoginService loginService=new LoginService();
        login=loginService.login(login);
        if (login == null) {
            System.out.println("index.jsp");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        } else {
            System.out.println("UserManagement.jsp");
            session.setAttribute("login", login);
            request.getRequestDispatcher("/UserServlet.action?flag=findUser").forward(request, response);
        }
    }
    protected void loginOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.invalidate();
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}
